import { memo, useCallback } from 'react';
import type { FC, PropsWithChildren } from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import {
  Button,
  Form,
  FormItemProps,
  message,
  Tooltip,
  TooltipProps,
} from 'antd';
import * as yup from 'yup';
import { alphaNumericRegexString, phoneRegexString } from '@/constants/regexp';
import { useAuthStore } from '@/store/authStore';
import { yupResolver } from '@hookform/resolvers/yup';
import QueueAnim from 'rc-queue-anim';
import RxButton from '@/components/RxForm/RxButton';
import RxCodeInput from '@/components/RxForm/RxCodeInput';
import RxInput from '@/components/RxForm/RxInput';
import RxPassword from '@/components/RxForm/RxPassword';
import { formatPhone } from '@/utils/format';
import {tooltip} from "@/pages/Login/components/EmailRegisterForm";

const schema = yup
  .object({
    phone: yup.string().matches(phoneRegexString, '手机格式错误').required(),
    password: yup
      .string()
      .matches(alphaNumericRegexString, '密码只能包含数字和字母')
      .min(8)
      .max(16),
    passwordConfirmation: yup
      .string()
      .oneOf([yup.ref('password')], '确认密码错误')
      .required(),
    code: yup.string().required(),
  })
  .required();

const defaultValues: API.PhoneRegisterParams = {
  phone: '',
  password: '',
  passwordConfirmation: '',
  code: '',
};

const PhoneRegisterForm: FC<PropsWithChildren<{ show?: boolean }>> = ({
  show,
}) => {
  const { control, handleSubmit, trigger, resetField, reset } =
    useForm<API.PhoneRegisterParams>({
      resolver: yupResolver(schema),
      defaultValues,
      mode: 'all',
      criteriaMode: 'all',
    });

  const {
    phoneRegister: { phoneRegister, loading },
  } = useAuthStore();

  const onsubmit: SubmitHandler<API.PhoneRegisterParams> = useCallback(
    (values) => {
      values.phone = formatPhone(values.phone);
      phoneRegister(values)
        .then(() => {
          reset();
        })
        .finally(() => {
          resetField('code');
        })
        .catch(() => {
          message.error('服务器错误，注册失败');
        });
    },
    []
  );
  const componentProps = {
    onFinish: handleSubmit(onsubmit),
    className: 'w-72 h-72',
  };

  return !show ? null : (
    <QueueAnim
      leaveReverse
      //@ts-ignore
      component={Form}
      componentProps={componentProps}
    >
      {show
        ? [
            <RxInput
              key={'phone'}
              name={'phone'}
              placeholder={'手机号'}
              control={control}
              addonBefore="+86"
            />,

            <RxPassword
              key={'password'}
              name={'password'}
              placeholder={'请输入登录密码'}
              control={control}
              tooltip={tooltip}
            />,
            <RxPassword
              key={'passwordConfirmation'}
              name={'passwordConfirmation'}
              placeholder={'确认密码'}
              control={control}
              tooltip={tooltip}
            />,
            <RxCodeInput
              key={'code'}
              name={'code'}
              placeholder={'验证码'}
              control={control}
              trigger={trigger}
            />,
            <div key={'submit'}>
              <RxButton loading={loading} />
            </div>,
          ]
        : null}
    </QueueAnim>
  );
};

export default memo(PhoneRegisterForm);
